import { ref } from 'vue'
import {
  getUserCreditLimitByOrderTip,
  getUserMainContactPersonOptionList,
  multipleUpdateUserCreditLimit,
} from '@/api/users'

/**
 * 授信额度表单服务
 */
export const useCreditLimitForm = () => {
  // 表单保存加载
  const formSaveLoading = ref(false)

  // 表单
  const form = ref<UserAPIRequest.UpdateUserCreditLimitForm>({
    creditLimit: '',
    creditLimitType: 1,
    settlementDeadline: '',
    userIds: [],
  })

  /**
   * 重置表单
   */
  const resetForm = () => {
    form.value = {
      creditLimit: '',
      creditLimitType: 1,
      settlementDeadline: '',
      userIds: [],
    }
  }

  /**
   * 表单保存
   */
  const formSave = async () => {
    formSaveLoading.value = true
    const res = await multipleUpdateUserCreditLimit(form.value)
    formSaveLoading.value = false
    return res.data
  }

  return {
    form,
    formSaveLoading,
    formSave,
    resetForm,
  }
}

/**
 * 获取公司授信额度（用于创建工单时判断是否允许创建）
 */
export const useGetUserCreditLimit = () => {
  // 获取授信额度加载
  const getCreditLimitLoading = ref(false)

  // 公司授信额度
  const userCreditLimitByOrderTip = ref<UserCreditLimitByOrderTip>({
    creditLimitType: 1,
    allowCreateOrderWithSureEndOrder: true,
    unpaidPrice: 0,
    limitType: null,
  })

  /**
   * 获取公司授信额度
   * @param {string} userId - 公司id
   */
  const getCreditLimit = async (userId: string) => {
    getCreditLimitLoading.value = true
    const res = await getUserCreditLimitByOrderTip(userId)
    userCreditLimitByOrderTip.value = res.data.data.row
    getCreditLimitLoading.value = false
  }

  return {
    getCreditLimitLoading,
    userCreditLimitByOrderTip,
    getCreditLimit,
  }
}

/**
 * 获主联系人下拉选项
 */
export const useGetMainContactPersonOptionList = () => {
  // 获取下拉选项加载
  const getOptionListLoading = ref(false)

  // 获取下拉选项请求参数
  const getOptionListParam = ref({
    id: '',
    name: '',
    page: 1,
    limit: 50,
  })

  // 下拉列表
  const optionList = ref<Array<UserMainContactPersonOption>>([])

  /**
   * 获取下拉选项列表
   */
  const getOptionList = async () => {
    getOptionListLoading.value = true
    const res = await getUserMainContactPersonOptionList(getOptionListParam.value)
    getOptionListLoading.value = false
    if (res.data.code === 20000) {
      optionList.value = res.data.data.rows
      return ''
    }
    return res.data.message
  }

  return {
    optionList,
    getOptionListParam,
    getOptionListLoading,
    getOptionList,
  }
}
